package org.jaaksi.view.tabview;

import android.widget.TextView;
import org.jaaksi.view.tabview.tabview.DateUtil;
import org.jaaksi.view.tabview.tabview.ITimeTabData;

/**
 * Created by Fcy on 2016/6/18.
 * 需要带着fromTime 和 endTime 去请求（时间戳：精确到s）
 * 外界只需要绑定两个TextView，不需要关心时间，在ontabchange回调中处理时间，发送请求
 */
public class TimeController implements ITimeTabData {
    private TextView tvFromTime, tvEndTime;
    private long mFromTime, mEndTime; // s
    private int[] mTimeKeyArr;

    public TimeController(int[] keyArr) {
        bindTimeKeyArr(keyArr);
    }

    public long getFromTime() {
        return mFromTime;
    }

    public long getEndTime() {
        return mEndTime;
    }

    public static TimeController getInstance(int[] keyArr) {
        return new TimeController(keyArr);
    }

    private void bindTimeKeyArr(int[] keyArr) {
        mTimeKeyArr = keyArr;
    }

    public void bindTimeTextView(TextView tvFromTime, TextView tvEndTime) {
        this.tvFromTime = tvFromTime;
        this.tvEndTime = tvEndTime;
    }

    /**
     * 设置自定义时间，根据时间选择器
     */
    public void setCustomTime() {
        // TODO
    }

    private void resetTimeUI() {
        if (mFromTime != 0) {
            tvFromTime.setText(DateUtil.getTimeStr(mFromTime));
        }
        if (mEndTime != 0) {
            tvEndTime.setText(DateUtil.getTimeStr(mEndTime));
        }
    }

    /**
     * @param position 选中的位置
     */
    public void resetTime(int position) {
        if (mTimeKeyArr != null && mTimeKeyArr.length > position) {
            // 计算出每个时间段的时间戳，直接赋值给mFromTime, mEndTime
            switch (mTimeKeyArr[position]) {
                case TODAY:
                    mEndTime = mFromTime = DateUtil.getCurrDayTime();
                    break;
                case WEEK:
                    mFromTime = DateUtil.getCurrMondayTime();
                    mEndTime = DateUtil.getCurrSundayTime();
                    break;
                case MOUTH:
                    mFromTime = DateUtil.getMinMonthTime();
                    mEndTime = DateUtil.getMaxMonthTime();
                    break;
                case CUSTOM:
                    mEndTime = mFromTime = 0;
                    if (mCustomTimeAction != null) {
                        // 在实现该接口的地方，根据用户自定义的时间调用 setCustomTime
                        mCustomTimeAction.selectCustomTime();
                    }
                    break;
            }

            resetTimeUI();
        }
    }

    private ICustomTimeAction mCustomTimeAction;

    public void setCustomTimeAction(ICustomTimeAction mCustomTimeAction) {
        this.mCustomTimeAction = mCustomTimeAction;
    }

    public interface ICustomTimeAction {
        void selectCustomTime();
    }
}
